<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Dcat\Admin\Form;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SettingController extends Controller
{
    /**
     * 设置
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header(trans('setting.labels.settings'))
            ->row($this->form());
    }

    /**
     * 更新设置
     *
     * @param Request $request
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function store(Request $request)
    {
        // 更新设置
        admin_setting($request->only([
            'test_time',
            'pre_score',
        ]));

        // 更新选题数量
        collect($request->get('categories'))
            ->pluck('selected_count', 'id')
            ->each(function ($selectedCount, $id) {
                Category::query()
                    ->where('id', $id)
                    ->where('question_count', '>=', $selectedCount)
                    ->update(['selected_count' => $selectedCount]);
            });

        // 清除分类缓存
        Cache::forget(Category::CACHE_KEY);

        return \Admin::json()->success('保存成功！')->refresh();
    }

    /**
     * 设置表单
     *
     * @return string
     */
    protected function form()
    {
        // 获取配置
        $setting = admin_setting();

        // 获取题库分类
        $categories = Category::getFromCache();

        $form = new Form();

        $form->number('test_time')->value($setting->get('test_time', 1))->min(1)->help('单位：分钟');
        $form->number('pre_score')->value($setting->get('pre_score', 1))->min(1);

        // 题库分类选题数量
        $form->table('categories', function (NestedForm $table) use ($categories) {
            /** @var Category $category 当前题库分类 */
            $category = $categories->get($table->getKey());

            // 设置行 ID
            $table->setKey($category ? $category->id : 0);

            $table->hidden('id');
            $table->text('name')->disable();
            $table->text('question_count')->disable();
            $table->number('selected_count')->min(0)->max(
                $category ? $category->question_count : 0
            );
        })->disableCreate()->disableDelete()->value($categories);

        return $form
            ->action(request()->fullUrl())
            ->disableHeader()           // 去掉顶部
            ->disableViewCheck()        // 去掉底部`查看`checkbox
            ->disableEditingCheck()     // 去掉底部`继续编辑`checkbox
            ->disableCreatingCheck()    // 去掉底部`继续创建`checkbox
            ->render();
    }
}
